﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MediaAutomatorLib.Helpers
{
    public class FileNode
    {
        private FileNode _parent;
        public FileNode Parent
        {
            get
            {
                if (_parent == null)
                {
                    String parentPath = NodePath.Substring(0, NodePath.LastIndexOf("\\") + 1);
                    _parent = new FileNode(parentPath);
                    _parent.FileType = this.FileType;
                }
                return _parent;
            }
        }

        public List<FileNode> ChildNodes { get; set; }

        public bool IsDirectory { get; private set; }
        public FileRecognizer.FileType FileType { get; set; }

        public String NodePath { get; set; }


        public FileNode(string path)
        {
            ChildNodes = new List<FileNode>();
            NodePath = path;

            if (Directory.Exists(path))
                IsDirectory = true;
            else if (File.Exists(path))
            {
                IsDirectory = false;
                FileType = FileRecognizer.Recognize(path);
            }
            else
            {
                throw new MediaAutomatorException("Invalid path: {0}", path);
            }

        }

        public String NodeName
        {
            get
            {
                var path = NodePath;

                if (IsDirectory && path.EndsWith("\\"))
                    path = path.Substring(0, path.Length - 1);

                return Path.GetFileName(path);
            }
        }

        public override string ToString()
        {
            if (IsDirectory)
                return String.Format("Directory ({0}): {1}", FileType, Path.GetDirectoryName(NodePath));
            switch (FileType)
            {
                case FileRecognizer.FileType.Movie:
                    return String.Format("Movie: {0}", Path.GetFileName(NodePath));
                case FileRecognizer.FileType.TvShow:
                    return String.Format("Tv Show: {0}", Path.GetFileName(NodePath));
                case FileRecognizer.FileType.Undefined:
                    return String.Format("Undefined media: {0}", Path.GetFileName(NodePath));
            }
            return base.ToString();
        }

    }
}
